package com.example.demo.interceptor;

import com.example.demo.config.DynamicDataSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DataSourceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String countryCode = request.getHeader("country-code");
        if ("country1".equals(countryCode)) {
            DynamicDataSource.setDataSource("primary");
        } else if ("country2".equals(countryCode)) {
            DynamicDataSource.setDataSource("secondary");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        DynamicDataSource.clearDataSource();
    }
}    